package com.ff.sca.suser.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ff.sca.admin.service.RedisService;
import com.ff.sca.common.aoplog.ControllerLog;
import com.ff.sca.common.base.BaseController;
import com.ff.sca.common.codeenum.CodeEnum;
import com.ff.sca.common.codeenum.OperateModule;
import com.ff.sca.common.codeenum.OperateType;
import com.ff.sca.common.entity.resmsg.LayuiTableResMsg;
import com.ff.sca.common.entity.resmsg.ResMsg;
import com.ff.sca.common.entity.ztree.MenuNode;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.IpUtil;
import com.ff.sca.common.util.JWT;
import com.ff.sca.common.util.VerificationCodeUtil;
import com.ff.sca.common.util.bcrypt.BCryptPasswordEncoder;
import com.ff.sca.suser.entity.ScaSysUser;
import com.ff.sca.suser.service.IScaSysUserService;
import com.ff.sca.suser.service.IScaUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * sca后台管理员用户 前端控制器
 * </p>
 *
 * @author gw
 * @since 2018-09-20
 */
@RestController
@RequestMapping("/scaSysUser")
public class ScaSysUserController extends BaseController {

    @Autowired
    private IScaSysUserService sysUserService;
    @Autowired
    private IScaUserRoleService userRoleService;
    @Autowired
    private RedisService redisService;

    /**
     * 获取当前登录用户
     *
     * @return
     */
    @RequestMapping(value = "/getCurLoginSysUser", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg LoginSysUser(HttpServletRequest req) {
        String userIp = IpUtil.getIpAddr(req);
        ScaSysUser user = JWT.unsign(redisService.getAppCache("manager_token_" + userIp), ScaSysUser.class);
        if (user != null) {
            user.setLoginPwd(null);
        }
        return resSuccess(user);
    }

    /**
     * 注销
     *
     * @param request
     * @return
     */
    @ControllerLog(
            description = "注销",
            module = OperateModule.SysUserManger,
            opType = OperateType.delete
    )
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg loginOut(HttpServletRequest request) {
        try {
            String userIp = IpUtil.getIpAddr(request);
            redisService.delCache("manager_token_" + userIp);
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 登录
     *
     * @param request
     * @param userName
     * @param loginPassword
     * @param vfCode
     * @return
     */
    @ControllerLog(
            description = "登录系统",
            module = OperateModule.SysUserManger,
            opType = OperateType.select
    )
    @ResponseBody
    @RequestMapping(value = "/sysUserLogin", method = RequestMethod.POST)
    public ResMsg sysUserLogin(HttpServletRequest request, String userName, String loginPassword, String vfCode) {
        try {
            if (CharUtil.isNotEmpty(vfCode) && CharUtil.isNotEmpty(userName) && CharUtil.isNotEmpty(loginPassword)) {
                String userIp = IpUtil.getIpAddr(request);
                ScaSysUser loginUser = getCurLoginSysUser(request);
                ScaSysUser s_user = sysUserService.selectOne(new EntityWrapper<ScaSysUser>().eq("user_name", userName));
                if (loginUser != null && loginUser.getUserName().equals(userName)) {
                    loginUser.setLoginPwd(null);//返回对象中密码置空再返回
                    JSONObject json = new JSONObject();
                    json.put("token", redisService.getAppCache("manager_token_" + userIp));
                    json.put("suser", loginUser);
                    return new ResMsg(CodeEnum.LOGIN_608.getCode(), CodeEnum.LOGIN_608.getMsg(), json);
                } else {
                    String redis_vfcode = redisService.getAppCache("manager_vfcode_" + userIp);
                    if (redis_vfcode != null && redis_vfcode != "" && redis_vfcode.equalsIgnoreCase(vfCode)) {
                        if (userName.equals(s_user.getUserName())) {
                            BCryptPasswordEncoder bcy = new BCryptPasswordEncoder();
                            if (bcy.matches(loginPassword, s_user.getLoginPwd())) {
                                //通过ip标记登录信息，使用jwt令牌验证用户
                                String token = JWT.sign(s_user, 1000L * 60l * 60L * 12);//12小时
//                                String token = JWT.sign(s_user, 1000L * 30l);//30秒

                                redisService.putAppCache("manager_token_" + userIp, token, 60, TimeUnit.MINUTES);
                                s_user.setLoginPwd(null);
                                JSONObject json = new JSONObject();
                                json.put("token", token);
                                json.put("suser", s_user);
                                return new ResMsg(CodeEnum.LOGIN_601.getCode(), CodeEnum.LOGIN_601.getMsg(), json);
                            } else {
                                //密码错误
                                return new ResMsg(CodeEnum.LOGIN_606.getCode(), CodeEnum.LOGIN_606.getMsg(), null);
                            }
                        } else {
                            //不存在用户
                            return new ResMsg(CodeEnum.LOGIN_605.getCode(), CodeEnum.LOGIN_605.getMsg(), null);
                        }
                    } else {
                        //验证码错误
                        return new ResMsg(CodeEnum.LOGIN_604.getCode(), CodeEnum.LOGIN_604.getMsg(), null);
                    }
                }
            } else {
                //请求错误
                return new ResMsg(CodeEnum.LOGIN_607.getCode(), CodeEnum.LOGIN_607.getMsg(), null);
            }
        } catch (Exception e) {
            //登录异常
            e.printStackTrace();
            return new ResMsg(CodeEnum.LOGIN_602.getCode(), CodeEnum.LOGIN_602.getMsg(), e.getMessage());
        }
    }

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/vfcode", method = RequestMethod.GET)
    @ResponseBody
    public void vfcode(HttpServletRequest request, HttpServletResponse response) {
        try {
            OutputStream out = response.getOutputStream();
            //禁止图像缓存
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            String vfcode = VerificationCodeUtil.createVerificationCode(out);
            String userIp = IpUtil.getIpAddr(request);
            redisService.putAppCache("manager_vfcode_" + userIp, vfcode, 5, TimeUnit.MINUTES);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 查看管理用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/suserInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg selSuserInfo(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                return resSuccess(sysUserService.selectById(id));
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }

    }

    /**
     * 删除系统管理员
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "删除管理员",
            module = OperateModule.SysUserManger,
            opType = OperateType.delete
    )
    @RequestMapping(value = "/delSysUser", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg delSysUser(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                Boolean result = sysUserService.deleteById(id);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 修改管理员信息
     *
     * @param suser
     * @return
     */
    @ControllerLog(
            description = "修改管理员信息",
            module = OperateModule.SysUserManger,
            opType = OperateType.modify
    )
    @RequestMapping(value = "/updSysUser", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg updSysUser(ScaSysUser suser) {
        try {
            if (CharUtil.isNotEmpty(suser.getId())) {
                if (CharUtil.isNotEmpty(suser.getLoginPwd())) {
                    BCryptPasswordEncoder bcy = new BCryptPasswordEncoder();
                    String pwd = bcy.encode(suser.getLoginPwd());
                    suser.setLoginPwd(pwd);
                }
                suser.setUpdateTime(new Date());
                boolean result = sysUserService.updateById(suser);
                if (result) {
                    return resSuccess(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 添加后台管理用户
     *
     * @param suser
     * @return
     */
    @ControllerLog(
            description = "新增管理员",
            module = OperateModule.SysUserManger,
            opType = OperateType.create
    )
    @RequestMapping(value = "/addSysUser", method = RequestMethod.POST)
    @ResponseBody
    public ResMsg addSysUser(ScaSysUser suser) {
        try {
            if (CharUtil.isNotEmpty(suser.getUserName()) && CharUtil.isNotEmpty(suser.getLoginPwd())) {
                List<ScaSysUser> suserList = sysUserService.selectList(new EntityWrapper<ScaSysUser>().eq("user_name", suser.getUserName()));
                if (suserList.size() > 0) {
                    return new ResMsg(CodeEnum.RES_700.getCode(), CodeEnum.RES_700.getMsg(), null);
                } else {
                    BCryptPasswordEncoder bcy = new BCryptPasswordEncoder();
                    String pwd = bcy.encode(suser.getLoginPwd());
                    suser.setLoginPwd(pwd);
                    suser.setCreateTime(new Date());
                    Boolean result = sysUserService.insert(suser);
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 获取后台管理员列表
     *
     * @param suser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sysUserList", method = RequestMethod.POST)
    public LayuiTableResMsg sysUserList(HttpServletRequest request, Integer page, Integer size, ScaSysUser suser) {
        try {
            Page<ScaSysUser> pageEntity = setPageInfo(page, size);
            EntityWrapper ew = new EntityWrapper<ScaSysUser>();
            if (CharUtil.isNotEmpty(suser.getMobile())) {
                ew.like("mobile", suser.getMobile().toString());
            }
            if (CharUtil.isNotEmpty(suser.getUserName())) {
                ew.like("user_name", suser.getUserName());
            }
            Page<ScaSysUser> suserList = sysUserService.selectPage(pageEntity, ew);
            long total = sysUserService.selectCount(ew);
            return resTableSuccess(total, suserList.getRecords());

        } catch (Exception e) {
            e.printStackTrace();
            return resTableError(0, e.getMessage());
        }
    }

    /**
     * 获取用户授权菜单列表 @Title: getUserMenuList @Description: TODO @param @param
     * userId @param @return 参数 @return ResMsg 返回类型 @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getUserMenuList", method = RequestMethod.POST)
    public ResMsg getUserMenuList(Integer userId, Integer pid) {
        try {
            if (CharUtil.isNotEmpty(userId)) {
                // 获取用户的菜单；
                List<MenuNode> userRoles = sysUserService.getUserMenuList(userId, pid);
                return resSuccess(userRoles);
            } else {
                return resfail(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


}
